import { Byte } from '../../api/io/Byte';
import { BattleReport } from './BattleReport';
import { BattleRecords } from './BattleRecords';
import { BattleResult } from './BattleResult';
import { ITimer } from '../../api/timer/ITimer';
import { IAsync } from '../../api/event/IAsync';



/**战斗数据记录属性枚举*/
export const enum E_BattleDatabase {
	/**战报*/
	REPORT = 0,
	/**记录*/
	RECORD = 1,
	/**结果*/
	RESULT = 2,
	/**枚举数量*/
	EnumCount = 3
}


/**战斗数据记录*/
export class BattleDatabase {
	/**事件ID*/
	public static readonly EVENT_ID = 'STRUCT_DATA_BATTLE_DATABASE_EVENT_ID';
	/**整体更新事件ID（部分只需要监听整体变化）*/
	public static readonly TOTAL_EVENT_ID = 'STRUCT_DATA_BATTLE_DATABASE_TOTAL_EVENT_ID';
	/**缓存池*/
	private static POOL: BattleDatabase[] = [];

	/**创建入口*/
	public static create(json?: string): BattleDatabase {
		const c = this.POOL.pop() || new BattleDatabase();
		c._destroyed = false;
		c.resetProperty();
		if (json) {
			c.parse(json);
		}
		return c;
	}


	/**已释放*/
	protected _destroyed = false;
	/**战报*/
	protected _report: BattleReport = null;
	/**记录*/
	protected _record: BattleRecords = null;
	/**结果*/
	protected _result: BattleResult = null;


	/**构建函数-私有，防止外部创建*/
	private constructor() {
	}


	/**释放*/
	public destroy(): void {
		if (this._destroyed) {
			return;
		}
		this._destroyed = true;
		this.resetProperty(true);
		if (BattleDatabase.POOL.indexOf(this) === -1) {
			BattleDatabase.POOL.push(this);
		}
	}

	/**战报*/
	public get report() {
		return this._report;
	}


	/**记录*/
	public get record() {
		return this._record;
	}


	/**结果*/
	public get result() {
		return this._result;
	}



	/**通过枚举获取值*/
	public getV(k: E_BattleDatabase): any {
		switch (k) {
			case E_BattleDatabase.REPORT: return this._report;
			case E_BattleDatabase.RECORD: return this._record;
			case E_BattleDatabase.RESULT: return this._result;
			default: return null;
		}
	}


	/**通过枚举设置值*/
	public setV(k: E_BattleDatabase, v: any): void {
		switch (k) {
			case E_BattleDatabase.REPORT: this._report = v; break;
			case E_BattleDatabase.RECORD: this._record = v; break;
			case E_BattleDatabase.RESULT: this._result = v; break;
			default: break;
		}
	}


	/**初始化*/
	public resetProperty(fromDestroy = false): void {
		//战报
		if (this._report) {
			this._report.destroy();
			this._report = null;
		}
		if (!fromDestroy) {
			this._report = BattleReport.create();
		}
		//记录
		if (this._record) {
			this._record.destroy();
			this._record = null;
		}
		if (!fromDestroy) {
			this._record = BattleRecords.create();
		}
		//结果
		if (this._result) {
			this._result.destroy();
			this._result = null;
		}
		if (!fromDestroy) {
			this._result = BattleResult.create();
		}
	}


	/**序列化*/
	public stringify(toString: boolean): string | any {
		const json: any = {};
		if (this._report) {
			json.report = this._report.stringify(false);
		}
		if (this._record) {
			json.record = this._record.stringify(false);
		}
		if (this._result) {
			json.result = this._result.stringify(false);
		}

		return toString ? JSON.stringify(json) : json;
	}


	/**反序列化*/
	public parse(jsonv: string | any): this {
		this.resetProperty();
		if (!jsonv) {
			return this;
		}
		const json = typeof (jsonv) === 'string' ? JSON.parse(jsonv) : jsonv;
		if (json.report) {
			this._report.destroy();
			this._report = BattleReport.create(json.report);
		}
		if (json.record) {
			this._record.destroy();
			this._record = BattleRecords.create(json.record);
		}
		if (json.result) {
			this._result.destroy();
			this._result = BattleResult.create(json.result);
		}
		return this;
	}


	/**序列化-二进制*/
	public toBytes(byte: Byte): void {
		if (!byte) {
			return;
		}
		this._report.toBytes(byte);
		this._record.toBytes(byte);
		this._result.toBytes(byte);
	}


	/**反序列化-二进制*/
	public fromBytes(byte: Byte): this {
		this.resetProperty();
		if (!byte) {
			return;
		}
		this._report.fromBytes(byte);
		this._record.fromBytes(byte);
		this._result.fromBytes(byte);
		return this;
	}


	/**克隆*/
	public clone(): BattleDatabase {
		const byte = Byte.createFromPool();
		this.toBytes(byte);
		byte.pos = 0;
		const clonev = BattleDatabase.create().fromBytes(byte);
		Byte.recoverToPool(byte);
		return clonev;
	}


	/**处理更新*/
	public processUpdate(jsonv: string): void {
		if (!jsonv) {
			return;
		}

		const eventID = BattleDatabase.EVENT_ID;
		const us = JSON.parse(jsonv);

		for (let i = 0, len = us.length; i < len;) {
			const idx = us[i];
			//战报
			if (idx === E_BattleDatabase.REPORT) {
				const fui: string = us[i + 1];
				if (this._report) {
					this._report.processUpdate(fui);
				}
				else {
					console.error('BattleDatabase report is null when update.');
				}
				IAsync.dispatch(eventID, idx);
				i += 2;
				continue;
			}
			//记录
			if (idx === E_BattleDatabase.RECORD) {
				const fui: string = us[i + 1];
				if (this._record) {
					this._record.processUpdate(fui);
				}
				else {
					console.error('BattleDatabase record is null when update.');
				}
				IAsync.dispatch(eventID, idx);
				i += 2;
				continue;
			}
			//结果
			if (idx === E_BattleDatabase.RESULT) {
				const fui: string = us[i + 1];
				if (this._result) {
					this._result.processUpdate(fui);
				}
				else {
					console.error('BattleDatabase result is null when update.');
				}
				IAsync.dispatch(eventID, idx);
				i += 2;
				continue;
			}

			console.error('[Struct Data] can not find enum in BattleDatabase with idx = ' + idx + ', version maybe wrong.')
		}

		//全更事件
		ITimer.callLater(this, this.dispatchTotalUpdate);
	}


	/**比对不一致结果*/
	public getCompareInfo(other: BattleDatabase): string {
		if (!other) {
			return null;
		}

		const updates: any[] = [];

		//战报
		{
			const ui = this._report.getCompareInfo(other._report);
			if (ui && ui.length > 0) {
				updates.push(E_BattleDatabase.REPORT, ui);
			}
		}
		//记录
		{
			const ui = this._record.getCompareInfo(other._record);
			if (ui && ui.length > 0) {
				updates.push(E_BattleDatabase.RECORD, ui);
			}
		}
		//结果
		{
			const ui = this._result.getCompareInfo(other._result);
			if (ui && ui.length > 0) {
				updates.push(E_BattleDatabase.RESULT, ui);
			}
		}

		const jsonv = updates.length === 0 ? null : JSON.stringify(updates);
		return jsonv;
	}


	/**全部更新*/
	protected dispatchTotalUpdate(): void {
		IAsync.dispatch(BattleDatabase.TOTAL_EVENT_ID, this.getV(0));
	}

}
